<!--
 * @Author: wangding
 * @Date: 2020-10-09 11:01:08
 * @LastEditTime: 2021-01-29 13:56:25
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \solaxcloud\src\components\common\baseTable.vue
-->
  
<!--        
  用法：同传统的element-table一样用,不使用af-table-column
  <baseTable  :data="data" border   stripe @selection-change="handleSelectionChange($event)" @change='change($event)' :column='column'  :select='true'>
     <template #mg_state="{data}">
       {{data.mg_state}}
     </template>
     <template #option="{data}">
       <div class="option-box">
         <el-button size='small' type="primary" icon="el-icon-edit" @click='editUsers(data)'></el-button>
         <el-button size='small' type="danger" icon="el-icon-delete" @click='deleteUsers(data)'></el-button>
         <el-button size='small' type="warning" icon="el-icon-setting" @click='editRoles(data)'></el-button>
       </div>
     </template>
   </baseTable>
-->
<template>
  <div class="baseTable-main-box">
    <el-table
        v-bind='$attrs' :data='data' :column='tableData.headerData' @selection-change="handleSelection"  :border="true" size='mini' :id='tableId'>
      <el-table-column type="expand" v-if='$attrs.expand'  > 
        <template slot-scope="props">
          <slot  name='expand' :data='props.row'>{{props.row}}</slot>
        </template>
      </el-table-column>
      <el-table-column
        type="selection"
        width="40px" align='center' v-if='$attrs.select' >
      </el-table-column>
      <el-table-column type="index" :index="indexMethod" :label="$t('pageNumber')" align='center'  width="60">
      </el-table-column>
      <!-- :min-width="item.min_width||''" -->
      <template v-for='(item,index) in tableData.headerData' >
        <el-table-column
        :prop="item.value"
        :label="item.title"
        :width='item.width || ""'
        :min-width="item.min_width||''"
        :key='index'
        :sortable='item.sortable?true:false'
        align='center'
        :selectable='checkSelectable'
        :resizable="true"
        fit
        >
          <template slot="header" slot-scope="scope">
            <span>{{item.title}}</span>
          </template>
          <template slot-scope="scope">
              <slot  :name='item.slot' :data='scope.row'>
                  {{isNot(scope.row[item.value])}}
              </slot>
          </template>
        </el-table-column>
      </template>
    </el-table>
  </div>
</template>
<script>
export default {
  data () {
    return {
      data: [],
      tableId:'',
      tableHeader:[]
    }
  },
  props:{
    data:{
      type:Array,
      default:()=>{return []}
    },
    column:{
      type:Array,
      default:()=>{return []}
    }
  },
  computed:{
    tableData(){
      let obj = {
        headerData:this.column,
        dataList:this.data
      }
      return obj
    }
  },
  watch:{
    tableData:{
      handler(nv,ov){
        console.log(nv,'tableData');
        let arr = []
        if(nv.dataList.length>0){
            let thw = this.getterTHWidth()
            if(thw.length>0){
              arr.push(thw)
            }
            console.log(thw,'表头各元素宽度');
            
            this.$nextTick(()=>{
              let tbs = document.querySelectorAll(`#${this.tableId} .el-table__body-wrapper .el-table__body tbody tr`)
              let tbw = []
              tbs.forEach(item=>{
                if(item.querySelectorAll('td').length > 0){
                  let tds = item.querySelectorAll('td')
                  let subtbw = []
                  tds.forEach(items =>{
                    if(items.children[0].children[0]){
                      subtbw.push(items.children[0].children[0].offsetWidth)
                    }else{
                      subtbw.push(items.children[0].offsetWidth)
                    }
                  })
                  if(subtbw.length>0){
                    tbw.push(subtbw)
                  }
                }
              })
              console.log(tbw,'表体每行各元素宽度');
              arr = [...arr,...tbw]
              console.log(arr,'表格每行各元素宽度');
              this.setTableWidth(arr)
            })
            

        }else{//没有数据的情况下，只计算表头宽度
          let thw = this.getterTHWidth()
          if(thw.length>0){
            arr.push(thw)
          }
        }
        this.tableHeader = JSON.parse(JSON.stringify(nv.headerData))
      },
      deep:true,
    }
  },
  mounted () {
      let that = this
      this.tableId = 'id'+this.rand(100000000,999999999)
      document.onkeydown = function(e){
          if(e.keyCode == 13 && that.$parent.query ){
            that.$parent.query()
          }
      }
  },
  methods: {
    //获取表头各元素宽度
    setTableWidth(arr){
      let tableWidth = []
      let setSum = 0
      let setTableWidth = 0
      if(arr.length>1){
        for(let i = 0;i<arr[0].length;i++){
          let max = 0
          for(let j=0;j<arr.length;j++){
            if(arr[j][i]>max){
              max = arr[j][i]
            }
          }
          tableWidth.push(max)
        }
        console.log(tableWidth,'tableWidth');
        if(tableWidth.length > 0){
          for(let a = 0;a<tableWidth.length;a++){
            setSum +=tableWidth[a]
          }
        }
        setTableWidth = document.querySelector(`#${this.tableId} .el-table__header-wrapper .el-table__header`).offsetWidth
        console.log(setSum,'setSum');
        console.log(setTableWidth,'setTableWidth');
        let num = (setTableWidth-setSum)/(tableWidth.length)
        console.log(num,'num');
        if(setTableWidth>setSum){
          for(let a = 0;a<this.tableData.headerData.length;a++){
              let widthNum = tableWidth[a+1] + num/2
              this.tableData.headerData[a]['width'] = (widthNum).toFixed(2)
          }
          console.log(this.tableData.headerData,'tableWidth11');
        }
        
      }
    },
    getterTHWidth(){
      let ths = document.querySelectorAll(`#${this.tableId} .el-table__header-wrapper .el-table__header thead tr th`)
      let thw = []
      ths.forEach(item =>{
        if(item.className != 'gutter'){
          if(item.children[0].children[0]){
            thw.push(item.children[0].children[0].offsetWidth)
          }else{
            thw.push(item.children[0].offsetWidth)
          }
        }
      })
      return thw
    },
    //获取表体各元素宽度
    getterTBWidth(){
      
      return thw
    },
    rand(min,max) {
        return Math.floor(Math.random()*(max-min))+min;
    },
    checkSelectable(row){
      return 1 == 2
    },
    handleSelection (val) {
      if (Object.keys(this.$listeners).indexOf('selection-change') !== -1) {
        this.$emit('selection-change', val)
      }
    },
    isNot(val){
      if(val === null || val === "" || val === undefined){
        return ' - '
      }else{
        return val
      }
    },
    indexMethod(index){
      let current=this.$parent.current;
      let size=this.$parent.size;
      if(current){
        if(current==1){
          return index+1; 
        }else{
          return index+1+size*(current-1);
        }
      }else{
        return index+1;
      }
    }
  }
}
</script>
<style lang="less">
.baseTable-main-box{
  .break-word-text{
    // white-space: nowrap;
    overflow: visible;
  }
  .el-table td, .el-table th {
      padding: 0px;
      }
  .el-table tr {
      background-color: #e4e4e4;
  }
  .el-table th {
      background-color: #666;
  }
  .el-table__footer-wrapper thead div, .el-table__header-wrapper thead div {
      background-color: #666;
      color: #fff;
  }
  .break-word-text{
    // word-wrap:break-word;
  }
  .el-table th>.cell{
    overflow: visible;
    white-space:nowrap;
    word-break: keep-all;
    // text-overflow: ellipsis;
    // // overflow: hidden;
    // max-width: 260px;
    // box-sizing: border-box;
    padding: 10px 0px;
  }
  .el-table .cell{
    // padding: 4px 2px;
    overflow: visible;
    white-space: nowrap;
    word-break: keep-all;
  }
  .el-table--border td,
  .el-table--border th{
    border-right:none;
  }
  // .el-table .cell {
  //   overflow: visible;
  // }
}
</style>
